package com.xgsm.fastdfsdemo.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.xgsm.fastdfsdemo.Bean.FastDfsFile;
import com.xgsm.fastdfsdemo.Service.FastDfsSercive;
import com.xgsm.fastdfsdemo.mapper.FastDfsFileMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/file")
@Api(value = "fastDFs分布式文件存储 -- 文件上传下载", description = "fastDFs分布式文件存储 -- 文件上传下载")
@CrossOrigin//跨域的意思
public class FileController {
    //FastFileStorageClient 直接注入就能用 fastdsf自带的
    @Resource
    private FastFileStorageClient fastFileStorageClient;
    @Autowired
    private FastDfsFileMapper fastDfsFileMapper;
    //fastDFS storage存储节点路径  xxxxxx：服务器ip
    @Value("${fdfsUrl.FASTDFSSERVERIMAGE}")
    private  String FASTDFSSERVERIMAGE;
    @Value("${fdfsUrl.COMMONPATH}")
    private  String COMMONPATH;
    @Autowired
    private FastDfsSercive fastDfsSercive;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 文件上传
     *
     * @return result
     */
    @ApiOperation("上传")
    @Async("asyncServiceExecutor")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Map<String, String> upload(@RequestPart("file") MultipartFile file) throws IOException {
        Map<String, String> map = fastDfsSercive.insertAndUpload(file);
        return map;
    }

    /**
     * 文件删除
     *
     * @param proName
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @ApiOperation("根据文件名字删除")
    public HashMap<String, Object> delete(@RequestParam String proName) {
        QueryWrapper<FastDfsFile> queryWrapper = new QueryWrapper<>();
        String s = redisTemplate.opsForValue().get(COMMONPATH + proName);
        String delPath = FASTDFSSERVERIMAGE + s.substring(0, s.indexOf(">"));
        if (s != null) {
            fastFileStorageClient.deleteFile(delPath);
            redisTemplate.delete(COMMONPATH + proName);
            String delId = s.substring(s.indexOf(">")+1, s.length());
            int id = Integer.parseInt(delId);
            FastDfsFile fastDfsFile = new FastDfsFile(id,null, null,1);
            fastDfsFileMapper.updateById(fastDfsFile);
        } else {
            queryWrapper.lambda().eq(FastDfsFile::getProName, proName);
            List<FastDfsFile> fastDfsFiles = fastDfsFileMapper.selectList(queryWrapper);
            for (FastDfsFile fa : fastDfsFiles
            ) {
                String path = FASTDFSSERVERIMAGE + fa.getProUrl();
                fastFileStorageClient.deleteFile(path);
                fa.setIsdel(1);
                fastDfsFileMapper.updateById(fa);
            }
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("msg", "大哥啦~~~！！，删除成功！");
        return result;
    }


    /**
     * 文件下载
     *
     * @param url 路径
     * @return
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    @ApiOperation("下载")
    public void downLoad(@RequestParam String url, HttpServletResponse response) throws IOException {
        byte[] bytes = this.downloadFile(url);
        /** TODO 这里只是为了整合fastdfs，所以写死了文件格式。需要在上传的时候保存文件名。下载的时候使用对应的格式 **/
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("SMKJ.jpg", "UTF-8"));
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public byte[] downloadFile(String fileUrl) throws IOException {
//      http://192.168.85.129:8888/group1/M00/00/00/wKhVgWORP16AcJceAAAUk7NNFOw361.png
        String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        System.out.println("======group======" + group);
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        System.out.println("========path:=========" + path);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] bytes = fastFileStorageClient.downloadFile(group, path, downloadByteArray);
        return bytes;
    }


    @RequestMapping(value = "/getall", method = RequestMethod.GET)
    @ApiOperation("获取全部或根据名字进行查询")
    public List<FastDfsFile> getAllFile(String proName) {
        List<FastDfsFile> fastDfsFiles = null;
        QueryWrapper<FastDfsFile> queryWrapper = new QueryWrapper<>();
        if (proName == null||"".equals(proName)) {
            queryWrapper.lambda().eq(FastDfsFile::getIsdel, 0);
            fastDfsFiles = fastDfsFileMapper.selectList(queryWrapper);
        } else {
            queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(FastDfsFile::getProName, proName).eq(FastDfsFile::getIsdel, 0);
            fastDfsFiles = fastDfsFileMapper.selectList(queryWrapper);
        }
        if (fastDfsFiles.size() > 0) {
            return fastDfsFiles;
        } else {
            return null;
        }
    }
}